#!/usr/bin/env python

# Carri: Jordi Carrillo's python modules
#
# Copyright (C) 2009 Jordi Carrillo Bosch
#
# This file is part of Carri Project.
#
# Carri is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Carri is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Carri.  If not, see <http://www.gnu.org/licenses/>.



import os,re
from optparse import OptionParser

class Walker:
    '''walks a directory structure looking for 
    files ending with specific suffixes or matching specific 
    regexes'''

    def __init__(self,rootpath = '.', **kwargs):
        '''
        Will create a Walker from path rootpath. Kwargs being a keyword 
        dictionary with keys "suffix" and "regexpars". If suffix keyword is specified 
        it will look for all those files ending with suffix from rootpath. If regexpars 
        is specified it will look for those files matching regexpars. In all cases the walk 
        is done recursively and top-down. If both suffix and regexpars are provided, suffix 
        takes preference. If no suffix and no regexpars, then will just make a list 
        of all files from rootpath recursively.

        @param rootpath: Begin walk from here
        @type rootpath: String
        '''
        
        self.rootpath = rootpath 
        self.suffix = None
        self.patfile = None
        for key,value in kwargs.iteritems():
            if key == 'suffix':
                self.suffix = value
            elif (key == 'regexpars' and isinstance(value,tuple)):
                self.patfile = apply(re.compile,value)
    
    def search(self):
        '''returns a searcher iterator 
        based on suffix or regex'''
        return self.__getWalkerFactory()

    def __getWalkerFactory(self):
        if self.suffix:
            return self.__walkSuffix()
        elif self.patfile:
            return self.__walkRegexFile()
        return self.__justWalk()
    
    def __justWalk(self):
        for curpath,dirs,files in os.walk(self.rootpath):
            for file in files:
                yield os.path.join(curpath,file)

    def __walkSuffix(self):
        for file in self.__justWalk():
            if file.endswith(self.suffix):
                yield file
    
    def __walkRegexFile(self):
        for file in self.__justWalk():
            if self.patfile.search(file):
                yield file
                

class Renamer:
    '''Class that implements file renaming taking into account 
    prefixes, suffixes, counts and increments'''
    def __init__(self,prefix,suffix,count = 0, increment = 1):
        '''
        Will create a Renamer, so files can be renamed following 
        the patterns prefix, suffix, count and increment

        @param prefix: file name prefix
        @type prefix: String

        @param suffix: Adds suffix to the file name
        @type suffix: String

        @param count: Begin counting from count, defaults 0
        @type count: int

        @param increment: Increment to add up to L{count}
        @type increment: int
        '''

        self.prefix = prefix
        self.suffix = suffix
        self.count = count
        self.increment = increment

    def rename(self,file):
        dirpath = os.path.dirname(file)
        destination = os.path.join(dirpath,self.prefix+str(self.count)+self.suffix)
        if os.path.exists(destination):
            return
        os.rename(file,destination)
        self.count += self.increment



if __name__=='__main__':
    parser = OptionParser()
    parser.add_option("-p","--path",dest="rootpath",help="Begin to search from path")
    parser.add_option("-s","--suffix",dest="suffix",help="Look for files ending with suffix")
    parser.add_option("-r","--regex",dest="regex",help="Look for files ending with suffix")

    options, args = parser.parse_args()
    rootpath = options.rootpath or '.'
    walker = Walker(rootpath,suffix = options.suffix, regexfile = options.regex)
    for file in walker.search():
        print file


